package Algorithm;

public class Day10 {
    public static int[] nextArray(char[] pattern) {
        int[] lps = new int[pattern.length];
        int j = 0;
        for(int i = 1; i < pattern.length; ) {
            if(pattern[i] == pattern[j]) {
                lps[i] = j + 1;
                i++;
                j++;
            } else {
                if(j != 0) {
                    j = lps[j-1];
                } else {
                    lps[i] = 0;
                    i++;
                }
            }
        }
        return lps;
    }

    public static void main(String[] args) {
        String haystack = "hello";
        String needle = "ll";
        int[] lps = nextArray(needle.toCharArray());
        int i = 0;
        int j = 0;
        int pos = -1;
        while(i < haystack.length() && j < needle.length()) {
            if(haystack.charAt(i) == needle.charAt(j)) {
                if(j == 0) {
                    pos = i;
                }
                i++;
                j++;
            } else {
                if(j != 0) {
                    j = lps[j-1];
                } else {
                    i++;
                }
            }
        }
        if(j == needle.length()) {
            System.out.println(pos);
        }
        System.out.println("-1");
    }
}
